package com.tingyuge.base.jdk.io.nio.socketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/8
 * @description
 */
public class ServerSocketChannelDemo {

    public static void main(String[] args) throws Exception {
        int port = 8888;
        ByteBuffer buffer = ByteBuffer.wrap("hello socket server".getBytes());

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        ServerSocketChannel channel = socketChannel.bind(new InetSocketAddress(port));


        channel.configureBlocking(false);
        //一直监听是否新的连接传入
        while (true){
            System.out.println("waiting for connections");
            SocketChannel socket = channel.accept();
            if(null == socket){
                System.out.println("没有新的连接");
                Thread.sleep(2000);
            }else {
                System.out.println("incoming connection from : "+ socket.getRemoteAddress());
                //指针指向0
                buffer.rewind();
                socket.write(buffer);
                socket.close();
            }



        }
    }
}
